package io.zerax.moyu_chat.protocol;
import java.util.Arrays;

public class MoyuPacket
{
    public static final byte[] MAGIC = "MOYU".getBytes();
	public static final int MAGIC_LEN = 4;
	public static final int NAME_LEN = 20;
	public static final int HEADER_LEN = 25;
	
	public String name;
	public MoyuOperator op;
	public String message;
	
    public MoyuPacket(String name, MoyuOperator op, String message) {
        this.name = name;
		this.op = op;
		this.message = message;
    }
	
	public byte[] encode() {
		byte[] pak = new byte[HEADER_LEN + message.length()];
		
				
		return pak;
	}
	
	public static MoyuPacket Decode(byte[] bytes) {
		if (bytes.length < HEADER_LEN) return null;
		if (!CheckMagic(bytes)) return null;
		
		
		return new MoyuPacket(GetName(bytes), GetOp(bytes), GetMessage(bytes));
	}
	
	private static boolean CheckMagic(byte[] bytes) {
		if (bytes.length < MAGIC.length) return false;
		for (int i = 0; i < MAGIC.length; i++) {
			if (bytes[i] != MAGIC[i]) return false;
		}
		
		return true;
	}
	
	private static String GetName(byte[] bytes) {
		return new String(bytes, MAGIC_LEN, NAME_LEN).trim();
	}
	
	private static MoyuOperator GetOp(byte[] bytes) {
		return Utils.fromByte(bytes[HEADER_LEN - 1]);
	}
	
	private static String GetMessage(byte[] bytes) {
		return new String(bytes, HEADER_LEN, bytes.length - HEADER_LEN);
	}
}
